package org.mv.mm.docs;

//Don't optimalize imports via NetBeans 7.1 IDE feature
import org.mv.mm.common.CentralLookup;
import org.mv.mm.api.data.IDataProvider;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mv.mm.api.Doc;
import org.mv.mm.api.Fragment;
import org.mv.mm.api.capabilities.ICreatableDocCapability;
import org.mv.mm.api.capabilities.ICreatableFragmentCapability;
import org.mv.mm.api.capabilities.IRefreshableDocViewCapability;
import org.mv.mm.api.capabilities.IReloadableDocCapability;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.openide.util.datatransfer.NewType;
import static org.mv.mm.docs.Bundle.*;

/**
 *
 * @author Martin
 */
@Messages({
  "LBL_NewDocWorkName_dialog=Document working title*:",
  "LBL_NewDocWorkNameError_dialog=Please, try another working title for the new document:",
  "TITLE_NewDoc_dialog=New document"})
public class DocNewType extends NewType {

  private final IDataProvider dataProvider;
  private final boolean root;
  private static final Logger logger = Logger.getLogger(DocNewType.class.getName());

  public DocNewType(IDataProvider dataProvider, boolean root) {
    this.dataProvider = dataProvider;
    this.root = root;
  }

  @Override
  public String getName() {
    return TITLE_NewDoc_dialog();
  }

  @Override
  public void create() throws IOException {
    // Use dialog for name of new doc
    Object result;
    String docWorkName;
    NotifyDescriptor.InputLine msg = new NotifyDescriptor.InputLine(LBL_NewDocWorkName_dialog(), TITLE_NewDoc_dialog());

    result = DialogDisplayer.getDefault().notify(msg);
    docWorkName = msg.getInputText();

    // Now if there is not any user input, it repeats the dialog.
    while (NotifyDescriptor.YES_OPTION.equals(result) && docWorkName.equals("")) {
      result = DialogDisplayer.getDefault().notify(msg);
      docWorkName = msg.getInputText();
    }
    if (!NotifyDescriptor.YES_OPTION.equals(result)) {
      return;
    }

    try {
      Doc doc = null;
      boolean firstTry = true;
      // Repeat, until user inputs unique workName
      while (doc == null) {
        if (!firstTry) {
          // Set a different message
          msg = new NotifyDescriptor.InputLine(LBL_NewFragmentWorkNameError_dialog(), TITLE_NewFragment_dialog());
          msg.setInputText(docWorkName);

          result = DialogDisplayer.getDefault().notify(msg);
          if (NotifyDescriptor.YES_OPTION.equals(result)) {
            docWorkName = msg.getInputText();
            // Repeat if the user inputs empty string
            while (docWorkName.equals("")) {
              result = DialogDisplayer.getDefault().notify(msg);
              if (!NotifyDescriptor.YES_OPTION.equals(result)) {
                return;
              } else {
                docWorkName = msg.getInputText();
              }
            }
          } else {
            return;
          }

        } else {
          firstTry = false;
        }

        //Pass the new data to the dataProvider's implementation of the create capability
        // and get new Doc, or null if the id field (workName) is not unique
        ICreatableDocCapability cec = dataProvider.getLookup().lookup(ICreatableDocCapability.class);
        doc = cec.create(docWorkName);
      }

      notifyRefreshable(doc);

    } catch (Exception ex) {
      logger.log(Level.SEVERE, null, ex); //TODO provide a message from Bundle
    }
  }

  private void notifyRefreshable(Doc doc) throws Exception {
    //Refresh the list of docs via the implementation of the reload capability: 
    IReloadableDocCapability r = dataProvider.getLookup().lookup(IReloadableDocCapability.class);
    r.reload();

    CentralLookup cl = CentralLookup.getDefault();
    Collection<? extends IRefreshableDocViewCapability> nodes = cl.lookupAll(IRefreshableDocViewCapability.class);
    for (IRefreshableDocViewCapability rvc : nodes) {
      rvc.refreshAfterNew();
    }
  }
}
